<template>
    <div class="app-container">
        <div style="padding-bottom: 10px">
            <el-row>
                <el-col :span="6">
                    <el-input v-model="filter.mobile" placeholder="请输入手机号">
                        <template slot="prepend">手机号</template>
                    </el-input>
                </el-col>
                <el-col :span="6" style="margin-left: 10px">
                    <el-input v-model="filter.name" placeholder="请输入姓名或昵称">
                        <template slot="prepend">姓名、昵称</template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button icon="el-icon-search" @click="handleFilter" />
                </el-col>
            </el-row>
        </div>
        <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%" @sort-change="sortChange">
            <el-table-column label="会员ID" prop="id" align="center" width="80">
                <template slot-scope="{ row }">
                    <span>{{ row.uid }}</span>
                </template>
            </el-table-column>
            <el-table-column label="头像" width="110px" align="center">
                <template slot-scope="scope">
                    <img :src="scope.row.avatar" style="height: 30px; width: 30px" :onerror="defaultAvatar">
                </template>
            </el-table-column>
            <el-table-column label="姓名、昵称" width="110px" align="center">
                <template slot-scope="{ row }">
                    <span>{{ row.realname ? row.realname : row.nickname }}</span>
                </template>
            </el-table-column>
            <el-table-column label="联系电话" width="110px" align="center">
                <template slot-scope="{ row }">
                    <span>{{ row.mobile }}</span>
                </template>
            </el-table-column>
            <el-table-column label="余额/积分" prop="credit2" width="120px" align="center" :class-name="getSortClass('credit2')">
                <template slot-scope="{ row }">
                    <span>{{ get_app_type() == 'we7' ? row.credit2 : row.balance }}/{{ get_app_type() == 'we7' ? parseIntegral(row.credit1) : parseIntegral(row.integral) }}</span>
                </template>
            </el-table-column>
            <el-table-column v-if="user_theme.district_on" label="地区" width="120px" align="center">
                <template slot-scope="{ row }">
                    <span>{{ row.district }}</span>
                </template>
            </el-table-column>
            <el-table-column v-if="user_theme.career_on" label="职业" width="120px" align="center">
                <template slot-scope="{ row }">
                    <span>{{ row.career }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column
        :label="$t('城市')"
        width="110px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.city }}</span>
        </template>
      </el-table-column> -->
            <el-table-column label="创建时间" :formatter="dateFormat" width="180px" align="center" prop="createtime" />
            <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{ row, $index }">
                    <el-button type="primary" size="mini" @click="handleMoney(row)">
                        余额
                    </el-button>
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        {{ $t('table.edit') }}
                    </el-button>
                    <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">
                        {{ $t("table.delete") }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogMoneyFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px">
                <el-form-item label="类型" prop="type">
                    <el-select v-model="temp.type">
                        <el-option label="余额充值" value="0">余额充值</el-option>
                        <el-option label="余额消费" value="1">余额消费</el-option>
                        <el-option label="积分充值" value="2">积分充值</el-option>
                        <el-option label="积分消费" value="3">积分消费</el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="temp.type === '0' || temp.type === '1'" :label="$t('余额')" prop="balance">
                    <el-input v-model="temp.balance" />
                </el-form-item>
                <el-form-item v-if="temp.type === '2' || temp.type === '3'" :label="$t('积分')" prop="integral">
                    <el-input v-model="temp.integral" />
                </el-form-item>
                <el-form-item label="说明" prop="desc">
                    <el-input v-model="temp.desc" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogMoneyFormVisible = false">
                    {{ $t("table.cancel") }}
                </el-button>
                <el-button type="primary" @click="createMoneyData()">
                    {{ $t("table.confirm") }}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import app_info from '@/app.conf'
import { fetchList, deleteUser } from '@/ucenter/api/user'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import moment from 'moment'

export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                published: 'success',
                draft: 'info',
                deleted: 'danger'
            }
            return statusMap[status]
        }
    },
    data() {
        const validateBalanceRequire = (rule, value, callback) => {
            if (value === '' && (this.temp.type === '0' || this.temp.type === '2')) {
                this.$message({
                    message: rule.message,
                    type: 'error'
                })
                callback(new Error())
            } else {
                callback()
            }
        }
        const validateIntegralRequire = (rule, value, callback) => {
            if (value === '' && (this.temp.type === '2' || this.temp.type === '3')) {
                this.$message({
                    message: rule.message,
                    type: 'error'
                })
                callback(new Error())
            } else {
                callback()
            }
        }
        return {
            // table
            user_theme: {
                district_on: false,
                career_on: false
            },
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                importance: undefined,
                title: undefined,
                type: undefined,
                sort: '-credit2'
            },

            defaultAvatar: 'this.src="' + require('@/assets/default_images/default-avatar.png') + '"',

            // filter
            filter: {
                mobile: '',
                name: ''
            },

            // edit 相关
            cur_user: {},

            // money
            temp: {
                type: '',
                balance: '',
                integral: '',
                desc: ''
            },
            dialogMoneyFormVisible: false,
            dialogStatus: '',
            rules: {
                type: [
                    { required: true, message: '请选择操作类型', trigger: 'change' }
                ],
                balance: [
                    { required: true, validator: validateBalanceRequire, message: '请输入有效余额', trigger: 'change' }
                ],
                integral: [
                    { required: true, validator: validateIntegralRequire, message: '请输入有效积分', trigger: 'change' }
                ],
                desc: [
                    { required: true, message: '请输入说明', trigger: 'change' }
                ]
            },

            textMap: {
                update: 'Edit',
                create: 'Create'
            },
            downloadLoading: false
        }
    },
    created() {
        this.getList()
    },
    methods: {
        get_app_type() {
            return app_info.type
        },
        parseIntegral(integral) {
            return parseInt(integral)
        },
        handleAdd() {
            this.$router.push('/crm/user/add')
        },
        dateFormat(row, column) {
            var date = row[column.property]
            if (date === undefined) {
                return ''
            }
            if (app_info.type == 'we7') {
                return moment(date * 1000).format('YYYY-MM-DD HH:mm:ss')
            } else {
                let d = new Date(date)
                return moment(d.getTime()).format('YYYY-MM-DD HH:mm:ss')
            }
        },
        getList() {
            this.listLoading = true
            let data = Object.assign({}, this.listQuery, this.filter)
            fetchList(data).then((response) => {
                this.list = response.data.items
                this.total = response.data.total

                // Just to simulate the time of the request
                setTimeout(() => {
                    this.listLoading = false
                }, 50)
            })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleModifyStatus(row, status) {
            this.$message({
                message: '操作成功',
                type: 'success'
            })
            row.status = status
        },
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'credit2') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+credit2'
            } else {
                this.listQuery.sort = '-credit2'
            }
            this.handleFilter()
        },
        resetTemp() {
            this.temp = {
                id: undefined,
                importance: 1,
                remark: '',
                timestamp: new Date(),
                title: '',
                status: 'published',
                type: ''
            }
        },
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogMoneyFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        handleUpdate(row) {
            this.$router.push('/crm/user/edit?uid=' + row.uid)
        },
        handleDelete(row, index) {
            this.$alert('请谨慎删除用户！', {
                callback: action => {
                    if (action == 'confirm') {
                        deleteUser({ uid: this.list[index].uid }).then(() => {
                            // this.list.unshift(this.temp);
                            // this.dialogMoneyFormVisible = false;
                            this.$notify({
                                title: '成功',
                                message: '删除成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.list.splice(index, 1)
                        })
                    }
                }
            })
        },
        handleDownload() {
            this.downloadLoading = true
            import('@/vendor/Export2Excel').then((excel) => {
                const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
                const filterVal = [
                    'timestamp',
                    'title',
                    'type',
                    'importance',
                    'status'
                ]
                const data = this.formatJson(filterVal)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: 'table-list'
                })
                this.downloadLoading = false
            })
        },
        formatJson(filterVal) {
            return this.list.map((v) =>
                filterVal.map((j) => {
                    if (j === 'timestamp') {
                        return parseTime(v[j])
                    } else {
                        return v[j]
                    }
                })
            )
        },
        getSortClass(key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        },
        handleMoney(row) {
            this.dialogMoneyFormVisible = true
            this.cur_user = row
        },
        createMoneyData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const data = this.temp
                    data.uid = this.cur_user.uid
                    operate(data).then(res => {
                        this.$notify({
                            title: '成功',
                            message: '操作成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.dialogMoneyFormVisible = false
                        this.getList()
                    })
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
@import url("~@/common/iconfont/iconfont.css");
</style>